<?php

namespace app\api\controller;

use app\api\model\GradeCharm;
use app\api\model\GradeNoble;
use app\api\model\GradeTycoon;
use app\api\model\RankingRecords;
use app\api\model\User;
use app\api\model\ClusterUser;
use app\api\model\GiftRecord;
use app\api\model\OrderCommon as Order;
use GatewayClient\Gateway;
use think\Db;
use think\Request;
use app\api\model\Cluster as ClusterModel;
use app\api\model\VolleyDesc as Balance;
use app\api\model\YaoqingRecords as Income;
use app\api\model\Clusterchat;
use app\api\model\Task;
use app\api\model\Gift;
use app\api\model\ConfigSystem as Config;

class Cluster extends Common
{
    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        exit(json_encode(['code'=>201, 'msg'=>'服务已关闭']));
    }
    public function status()
    {
        $data = ClusterModel::get(['id' => $this->params['id'], 'types' => 2, 'status' => 1]);

        if (!$data) return $this->return['common.error.notExist'];

        $where = ['cluster_id' => $this->params['id'], 'user_id' => $this->params['user_id']];

        if ($this->params['status']) {
            $result = Db::name('cluster_user')->where($where)->find();
            if (!$result) {
                $where['status'] = 1;
                $where['create_time'] = time();
                $where['update_time'] = time();
                Db::name('cluster_user')->insert($where);

                ClusterModel::where(['id' => $this->params['id']])->setInc('count');
            }
        } else {
            Db::name('cluster_user')->where($where)->delete();
            ClusterModel::where(['id' => $this->params['id']])->setDec('count');
        }

        return $this->return['common.success.default'];
    }

    public function lists(Request $request = null)
    {
        $where = 'types =2 and status = 1';
        $order = 'count desc';

        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 10;
        $page = ($page - 1) * $pagesize;

        $field = 'id, name, count, logo, description';

        $sql = "select $field from cluster where $where order by $order limit $page, $pagesize";

        $data = Db::query($sql);

        return $this->pass($data);
    }

    public function users(Request $request = null)
    {
        $page = $request->param('page') ?: 1;
        $page = ($page - 1) * 10;

        $data = Db::query("select t1.ban_chat, t1.identity, t2.id, t2.name, t2.head_100 avatar, t2.sex, t2.age, t2.tycoon, t2.charm_value, t2.noble_time, t2.noble_grade 
        from cluster_user t1,user t2 where t2.id=t1.user_id and t1.cluster_id=" . $this->params['id'] . " and t1.status = 1 order by t1.identity = 0,t1.identity asc limit $page,10");

        foreach ($data as $key => $item) {
            $data[$key]['avatar'] = changeUrl($item['avatar']);

            // 土豪
            $gradeTycoon = GradeTycoon::where(['min' => ['elt', $item['tycoon']]])->order('grade desc')->find();
            $data[$key]['tycoonGrade'] = $gradeTycoon->grade;
            $data[$key]['tycoonIcon'] = changeUrl($gradeTycoon->icon);

            // 魅力
            $gradeCharm = GradeCharm::where(['min' => ['elt', $item['charm_value']]])->order('grade desc')->find();
            $data[$key]['charmGrade'] = $gradeCharm->grade;
            $data[$key]['charmIcon'] = changeUrl($gradeCharm->icon);

            if ($item['noble_time'] > time() && $item['noble_grade']) {
                $data[$key]['is_noble'] = 1;

                $gradeNoble = GradeNoble::get(['grade' => $item['noble_grade']]);

                $data[$key]['noble_icon'] = $gradeNoble ? changeUrl($gradeNoble['icon']) : '';
            } else {
                $data[$key]['is_noble'] = 0;
                $data[$key]['noble_icon'] = '';
            }

            unset($data[$key]['noble_time'], $data[$key]['noble_grade']);
        }

        return $this->pass($data);
    }

    public function addTalk()
    {
        $Cluster = ClusterModel::get($this->params['cluster_id']);

        $result = ClusterUser::get(['cluster_id' => $this->params['cluster_id'], 'user_id' => $this->member['id'], 'status' => 1]);

        if (!$result) return $this->return['common.error.noPermission'];
        if ($result['ban_chat']) return $this->miss('已被群管理禁言');

        if (!in_array($this->params['type'], [5,8])) {
            if (!isset($this->params['content']) || !$this->params['content']) {
                return $this->miss('内容不能为空');
            }
        }

        if (isset($this->params['content'])) {
            $this->params['content'] = strip_tags($this->params['content']);
        }

        $contain = [
            'cluster_id' => $this->params['cluster_id'],
            'userid' => $this->member['id'],
            'type' => $this->params['type'],
            'content' => $this->params['content'] ?? '',
            'data' => $this->params['data'] ?? '',
            'relates' => $this->params['relates'] ?? '',
        ];

        switch ($this->params['type']) {
            case 0:
                $filter = Db::name('filter_word')->where(['state' => 1])->column('name');
                foreach ($filter as $v) {
                    if (stripos($this->params['content'], $v) !== false) {
                        return $this->miss('消息含有敏感词"' . $v . '",请重新编辑发送');
                    }
                }

                $contain['is_top'] = $this->params['is_top'] ?? 0;

                if ($contain['is_top']) {
                    $config = Config::index('cluster');

                    if ($this->member['volley'] < $config['top_price']) return $this->return['user.error.insufficientBalance'];
                    Balance::index($this->member['id'], $config['top_price'], '发送置顶消息');
                }

                //Clusterchat::create($contain);

                break;
            case 1:
                if (isset($this->params['is_burn'])) {
                    $contain['is_burn'] = $this->params['is_burn'];
                }

                //Clusterchat::create($contain);

                $msg = '[图片]';

                break;
            case 2:
                $contain['second'] = $this->params['second'];

                //Clusterchat::create($contain);

                $msg = '[语音]';

                break;
            case 3:
                $contain['data'] = json_encode(['cover' => $this->params['cover']]);

                //Clusterchat::create($contain);

                $msg = '[视频]';
                break;
            case 5: # 拼手气红包
                $money = input('money');
                $count = input('count/d');
                $ways = input('ways') ?? 1; # 1余额|2支付宝|3微信

                if ($money <= 0) {
                    return $this->miss('红包金额不正确');
                }

                if (!$this->member['paypwd']) {
                    return $this->miss('尚未提现密码');
                }

                if (!isset($this->params['paypwd'])) {
                    return $this->miss('请先输入提现密码');
                }

                if(!password_verify($this->params['paypwd'], $this->member['paypwd'])) {
                    return $this->miss('提现密码错误');
                }

                $min = $money / 0.01;

                $min_count = $Cluster['count'] < $min ? $Cluster['count'] : $min;

                if ($count > $min_count) {
                    return $this->miss('红包人数范围在：1 - ' . $min_count);
                }

                $time = time();
                $number = uniqid();

                $chat_data = [
                    "cluster_id" => $this->params['cluster_id'],
                    "userid" => $this->member['id'],
                    "type" => $this->params['type'],
                    "content" => $contain['content'] ?: '恭喜发财，大吉大利',
                    'money' => $money,
                    'finish' => 1,
                    "data" => json_encode(['money' => $money, 'count' => $count]),
                ];
                $order_data = [
                    'number' => $number,
                    'user_id' => $this->member['id'],
                    'money' => $money,
                    'create_time' => $time,
                    'update_time' => $time,
                ];

                if ($ways == 1) {
                    if ($this->member['volley'] < $money) {
                        return $this->return['user.error.insufficientBalance'];
                    }

                    $chat = Clusterchat::create($chat_data);

                    $order_data['status'] = 1;
                    $order_data['data'] = json_encode(['id' => $chat->id]);
                    Db::name('order_common')->insert($order_data);

                    Balance::index($this->member['id'], $money, '发群红包');

                    $max = $money - ($count - 1) * 0.02;
                    $ids = redEnvelope('0.01', $max, $count, $money);

                    $rewards = [];
                    foreach ($ids as $n) {
                        $rewards[] = ['chat_id' => $chat->id, 'money' => $n, 'create_time' => $time, 'update_time' => $time];
                    }

                    Db::name('cluster_red_packet')->insertAll($rewards);
                } else {
                    return $this->miss('不支持的扣费方式');
                }
                break;
            case 6:

                //Clusterchat::create($contain);

                $msg = '[位置]';
                break;
            case 8:
                $gift = Gift::get($this->params['id']);
                if (!$gift) return $this->return['common.error.notExist'];

                if ($gift['types'] == 2) {
                    if (!$this->member['noble_grade'] || $this->member['noble_time'] < time()) {
                        return $this->miss('需先开通会员');
                    }
                }

                $money = $gift['price'] * $this->params['num'];

                if ($this->member['volley'] < $money) return $this->return['user.error.insufficientBalance'];

                $toUser = User::get($this->params['touserid']);

                $contain['money'] = $money;
                $contain['score'] = $money * 1;
                $contain['finish'] = 1;
                $contain['data'] = json_encode([
                    'money' => $money,
                    'id' => $this->params['id'],
                    'cover' => $gift['cover'],
                    'num' => $this->params['num'],
                    'name' => $gift['name'],
                    'preview' => $gift['preview'],
                    'videourl' => $gift['videourl'],
                    'videojson' => $gift['videojson'],
                    'to_user' => $this->params['touserid'],
                    'to_user_name' => $toUser['name']
                ]);

                Order::index(4,$this->member['id'],$money,1,json_encode(['id' => $this->params['id'], 'touserid' => $this->params['touserid'], 'num' => $this->params['num']]),1);

                GiftRecord::create([
                    'num' => $this->params['num'],
                    'gift_id' => $this->params['id'],
                    'user_id' => $this->member['id'],
                    'to_user' => $this->params['touserid'],
                ]);

                $remark = '给 ' . $toUser['name'] . '(' . $toUser['id'] . ') 赠送' . $gift['name'] . 'X'.$this->params['num'];
                Balance::index($this->member['id'], $money, $remark);

                $cluster_types = $Cluster['types'] == 1 ? '家族' : '群聊';
                $fencheng_content = '收获'.$cluster_types.'成员 ' . $this->member['name'] . '(' . $this->member['id'] . ') 赠送的礼物：' . $gift['name'] . 'X' . $this->params['num'];
                User::changeIntimate($this->member['id'], $toUser['id'], $money * 1, $fencheng_content, '', 1, 0, 'gift');

                // 族长礼物分成
                /*if ($Cluster['types'] == 1) {
                    $config = Config::index('family');
                    if ($config['gift_rate'] > 0) {
                        Income::index($this->member['id'], $Cluster['user_id'], $config['gift_rate'] * $money, '家族礼物', 1);
                    }
                }*/

                // 榜单记录
                $records_types = $toUser['sex'] == '女' ? '1,2,3,5,6' : '1,3,4,5,6';
                RankingRecords::index($records_types, $this->member['id'], $this->params['touserid'], $money);

                // 群威望
                ClusterModel::active($this->params['cluster_id'], $money);

                break;
        }

        if ($this->params['type'] != 5) {
            $chat = Clusterchat::create($contain);
        }

        // 任务
        if ($Cluster['types'] == 2) {
            Task::finish('cluster_chat', $this->member['id']);
        }

        $this->getNewMsg($chat->id);

        $request = request();
        $url = $request->domain() . str_replace('/index.php', '', $request->baseFile()) . '/apis/home/privatechat/getOtherList';

        $ids = Db::name('cluster_user')->where(['cluster_id' => $this->params['cluster_id'], 'status' => 1])->column('user_id');

        if ($ids) {
            $ids = Db::name('user')->where(['id' => ['in', $ids], 'is_online' => 1])->column('id');

            foreach ($ids as $item) {
                $datas = json_encode(['userid' => $item, 'count' => '', 'type' => ''], JSON_UNESCAPED_UNICODE);
                sendcurl($url, $datas, 0);
            }
        }
    }

    public function getNewMsg($id)
    {
        $clusterchat = Clusterchat::get($id);
        $cluster_id = $clusterchat['cluster_id'];

        $cluster = ClusterModel::get($cluster_id);


        $users = ClusterUser::where(['cluster_id' => $cluster_id, 'status' => 1])->column('user_id');

        foreach ($users as $key => $item) {
            $isRead = explode(',', $clusterchat['isRead']);

            if (in_array($item, $isRead)) {
                unset($users[$key]);
            }
        }

        $gradeNoble = Db::name('grade_noble')->where(['id' => ['gt', 0]])->column('id, icon, circle');

        $sql = "SELECT t1.head_100 as head_portrait,t.second,t1.name,t.content,t1.age, t1.sex, t1.noble_grade, t1.noble_time, 
                    t.id, t.data, t.isRead, t.is_burn, t.status, t.state,t.type,t.addtime,t.userid, t.is_top, t.is_burn  
                    FROM clusterchat t, user t1 
                    WHERE t.cluster_id=" . $cluster_id . " AND t.status not in (-1,2) AND (t.type <> -1 AND t.state <> 1) AND t.userid=t1.id ORDER BY t.id desc limit 0,1";
        $new = Db::query($sql);

        foreach ($users as $item) {
            $contain = ['new' => [], 'recall' => [], 'users' => ['userid' => $cluster['user_id'], 'touserid' => $item, 'cluster_id' => $cluster_id]];

            $data = $new;

            foreach ($data as $m => $n) {
                $data[$m]['addtime'] = strtotime($n['addtime']);

                $data[$m]['self'] = $item == $n['userid'] ? 1 : 0;
                $data[$m]['data'] = json_decode($n['data'],true);

                $data[$m]['is_noble'] = 0;
                $data[$m]['noble_icon'] = $data[$m]['noble_circle'] = '';
                if ($n['noble_time'] > time() && isset($gradeNoble[$n['noble_grade']])) {
                    $data[$m]['noble_icon'] = $gradeNoble[$n['noble_grade']]['icon'];
                    $data[$m]['noble_circle'] = $gradeNoble[$n['noble_grade']]['circle'];

                    $data[$m]['is_noble'] = 1;
                }
            }

            if ($data) {
                $contain['new'] = $data;
            }

            if (!empty($contain['new']) || !empty($contain['recall'])) {
                $message = json_encode(['code' => 200, 'action' => 'api/Cluster/getNewMsg', 'data' => $contain]);
            } else {
                $message = json_encode(['code' => 400, 'action' => 'api/Cluster/getNewMsg', 'data' => []]);
            }

            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $item, $message);
        }
    }

    public function getMsgList(Request $request = null)
    {
        $relate = input('relate/d') ?: 0;
        $page = $request->param('page') ?: 1;
        $pagesize = $request->param('pagesize') ?: 20;
        $page = ($page - 1) * $pagesize;


        $lastTime = date('Y-m-d H:i:s');

        $gradeNoble = Db::name('grade_noble')->where(['id' => ['gt', 0]])->column('id, icon, circle');

        if ($relate) {
            $where = " and t.type = 0 and FIND_IN_SET(".$this->member['id'].",t.relates) ";
        } else {
            $where = "";
        }

        $sql = "select t1.head_100 as head_portrait, t1.name, t1.age, t1.sex, t1.noble_grade, t1.noble_time, t.content, t.is_burn,
                t.id, t.type, t.userid, t.isRead, t.second, t.status, t.state, t.data, t.addtime, t.relates,t.clicks, t.is_top,
                TIMESTAMPDIFF(SECOND,t.addtime,NOW()) AS rowsecond, 
                TIMESTAMPDIFF(MINUTE,t.addtime,NOW()) as minute, 
                TIMESTAMPDIFF(HOUR,t.addtime,NOW()) as hour , 
                TIMESTAMPDIFF(DAY,t.addtime,NOW()) as day, 
                TIMESTAMPDIFF(WEEK,t.addtime,NOW()) as week 
                from clusterchat t, user t1 where t1.id = t.userid $where and t.cluster_id = " . $this->params['cluster_id'] . " 
                and status not in (-1,1) order by t.id desc limit $page, $pagesize";

        $result = Db::query($sql);

        $clusterRedPacket = Db::name('cluster_red_packet')->where(['user_id' => $this->member['id'], 'status' => 1])->column('chat_id');

        $relate_ids = [];
        for ($i = sizeof($result) - 1; $i >= 0; $i--) {
            $isRead = $result[$i]['isRead'];

            $isReadArr = explode(',', $isRead);

            if (!in_array($this->member['id'], $isReadArr) && $result[$i]['userid'] != $this->member['id']) {
                $isReadArr[] = $this->member['id'];

                $isReadStr = trim(implode(',', $isReadArr),',');

                Clusterchat::update(['id' => $result[$i]['id'], 'isRead' => $isReadStr]);
            }
            if ($this->member['id'] == $result[$i]['userid']) {
                $result[$i]['self'] = 1;
            } else {
                $result[$i]['self'] = 0;
            }

            $result[$i]['showtime'] = false;


            // 设置时间样式
            //$row = $row[0];
            $row = $result[$i];
            $addtime = $row['addtime'];
            $smalltime = explode(" ", $addtime);
            $smalltime = $smalltime[1];
            $second = floor(strtotime($lastTime) - strtotime($addtime));

            $result[$i]['addtime'] = strtotime($result[$i]['addtime']);

            $result[$i]['showtime'] = $second > 300;

            $lastTime = $row['addtime'];
            if ($row['week'] > 1) {
                $addtime = $row['addtime'];
            } elseif ($row['week'] == 1) {
                $addtime = '1周前';
            } elseif ($row['day'] > 0) {
                $addtime = $row['day'] . '天前';
            } elseif ($row['hour'] > 0) {
                $day = strtotime($row['addtime']) < strtotime(date('Ymd')) ? '昨天' : '今天';
                $addtime = $day . " " . $smalltime;
            } elseif ($row['minute'] > 0) {
                $addtime = $row['minute'] . '分钟前';
            } elseif ($row['rowsecond'] > 0) {
                $addtime = $row['rowsecond'] . '秒前';
            }
            $row['addtime'] = $addtime;
            $result[$i]['time'] = $row['addtime'];

            $result[$i]['data'] = json_decode($result[$i]['data'], true);

            if ($result[$i]['type'] == 5) {
                if (in_array($result[$i]['id'], $clusterRedPacket)) {
                    $result[$i]['state'] = 1;
                }
            }

            $result[$i]['noble_icon'] = $result[$i]['noble_circle'] = '';
            $result[$i]['is_noble'] = 0;
            if ($result[$i]['noble_time'] > time() && isset($gradeNoble[$result[$i]['noble_grade']])) {
                $result[$i]['noble_icon'] = $gradeNoble[$result[$i]['noble_grade']]['icon'];
                $result[$i]['noble_circle'] = $gradeNoble[$result[$i]['noble_grade']]['circle'];

                $result[$i]['is_noble'] = 1;
            }

            if ($relate) {
                $clicks = explode(',',$result[$i]['clicks']);

                if (!in_array($this->member['id'], $clicks)) {
                    $clicks = $result[$i]['clicks'] ? $result[$i]['clicks'] . ',' . $this->member['id'] : $this->member['id'];
                    $relate_ids[] = ['id' => $result[$i]['id'], 'clicks' => $clicks];
                }
            }

            unset($result[$i]['noble_grade'], $result[$i]['noble_time'], $result[$i]['rowsecond'], $result[$i]['minute'], $result[$i]['hour'],
                $result[$i]['day'], $result[$i]['week']);
        }

        if ($relate_ids) {
            foreach ($relate_ids as $key => $item) {
                Db::name('clusterchat')->where(['id' => $item['id']])->setField('clicks', $item['clicks']);
            }
        }

        $ids = array_column($result, 'id');
        array_multisort($ids,SORT_ASC,$result);

        //$result = array($result);

        return $this->pass($result);
    }

    public function changeread()
    {
        $data = Db::name('clusterchat')->where(['cluster_id' => $this->params['cluster_id']])->select();

        foreach ($data as $key => $item) {
            $isReadArr = explode(',', $item['isRead']);

            if (!in_array($this->member['id'], $isReadArr)) {
                $isReadArr[] = $this->member['id'];

                $isReadStr = trim(implode(',', $isReadArr),',');

                Clusterchat::update(['id' => $item['id'], 'isRead' => $isReadStr]);
            }
        }

        $message = json_encode(['code' => 200, 'action' => 'api/Cluster/changeread', 'data' => ['touserid' => $this->member['id']]]);

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $this->member['id'], $message);   // 实时显示消息是否已读
    }

    public function ranking()
    {
        $data = ClusterModel::get(['id' => $this->params['id']]);

        if (!$data) return $this->return['common.error.notExist'];

        $where = [
            't1.cluster_id' => $this->params['id'],
            't1.status' => 1
        ];

        if ($this->params['types'] == 3) {

            $ids = Db::name('cluster_user t1')->where($where)->column('user_id');

            if ($ids) {
                $data = [];
                $contain = [];
                $users = Db::name('user_intimate')->order('intimate desc')->select();

                foreach ($users as $key => $item) {
                    if (count($data) >= 20) {
                        break;
                    }

                    $couple_a = explode(',',$item['couple_a']);

                    if (in_array($couple_a[0], $ids) && in_array($couple_a[1], $ids)) {
                        $data[] = [$couple_a[0], $couple_a[1], $item['intimate']];
                        $contain[] = $couple_a[0];
                        $contain[] = $couple_a[1];
                    }
                }

                if ($contain) {
                    $contain_users = Db::name('user')->where(['id' => ['in', $contain]])->column('id, name, head_100');

                    foreach ($data as $key => $item) {
                        $couple = [];

                        if (array_key_exists($item[0], $contain_users)) {
                            $couple['user1_name'] = $contain_users[$item[0]]['name'];
                            $couple['user1_avatar'] = $contain_users[$item[0]]['head_100'];
                        } else {
                            $couple['user1_name'] = '未知';
                            $couple['user1_avatar'] = '';
                        }

                        $couple['user2_id'] = $item[1];
                        if (array_key_exists($item[0], $contain_users)) {
                            $couple['user2_name'] = $contain_users[$item[1]]['name'];
                            $couple['user2_avatar'] = $contain_users[$item[1]]['head_100'];
                        } else {
                            $couple['user2_name'] = '未知';
                            $couple['user2_avatar'] = '';
                        }

                        $couple['intimate'] = $item[2];

                        $data[$key] = $couple;
                    }
                }
            } else {
                $data = [];
            }
        } else {

            if ($this->params['types'] == 1) {
                $field = 'volley';
            } else if ($this->params['types'] == 2) {
                $field = 'charm_value';
            }

            $data = Db::name('cluster_user t1')
                ->join('user t2', 't2.id = t1.user_id')
                ->field('t1.user_id, t2.name, t2.head_100')
                ->where($where)
                ->order('t2.' . $field . ' desc')
                ->page(1,20)->select();
        }

        return $this->pass($data);
    }

    // 领取手气红包
    public function receive()
    {
        $result = Db::name('cluster_red_packet')->where(['chat_id' => $this->params['chat_id'], 'user_id' => $this->member['id']])->find();

        $data = [];
        if ($result) {
            $data['reward'] = $result['money'];
            $data['new_receive'] = 0;
        } else {
            $reward = Db::name('cluster_red_packet')->where(['chat_id' => $this->params['chat_id'], 'status' => 0])->orderRaw('rand()')->find();

            if (!$reward) {
                $data['reward'] = 0;
            } else {
                $data['reward'] = $reward['money'];

                Db::name('cluster_red_packet')->where(['id' => $reward['id']])->update(['user_id' => $this->member['id'], 'status' => 1, 'update_time' => time()]);

                Balance::index($this->member['id'], $reward['money'], '领取群红包', 1);
            }

            $data['new_receive'] = 1;
        }

        $lists = Db::name('cluster_red_packet t1')
            ->field('t1.id, t1.money, t1.update_time time, t2.name, t2.head_100 avatar')
            ->join('user t2', 't2.id = t1.user_id')
            ->where(['t1.chat_id' => $this->params['chat_id'], 't1.status' => 1])->select();

        foreach ($lists as $key => $item) {
            $lists[$key]['time'] = date('Y-m-d H:i:s', ($item['time']));
            $lists[$key]['avatar'] = changeUrl($item['avatar']);
        }

        $data['lists'] = $lists;

        return $this->pass($data);
    }

    // 红包领取状态
    public function receiveStatus()
    {
        $result = Db::name('cluster_red_packet')->where(['chat_id' => $this->params['chat_id'], 'user_id' => $this->member['id']])->find();

        if ($result) {
            $data = ['status' => 1, 'money' => $result['money']];
        } else {
            $data = ['status' => 0, 'money' => ''];
        }

        return $this->pass($data);
    }

    // @我的数量
    public function relateCount()
    {
        $cluster_id = $this->params['cluster_id'];
        $user_id = $this->member['id'];

        $sql = "select count(*) count from clusterchat where cluster_id = $cluster_id and type = 0 and FIND_IN_SET($user_id,relates) and clicks not like '%{$user_id}%'";

        $count = Db::query($sql)[0]['count'];

        return $this->pass(['count' => $count]);
    }

    // 进入家族群聊 聊天窗口展示贵族或座驾图标
    public function enter()
    {
        $ids = ClusterUser::where(['cluster_id' => $this->params['cluster_id'], 'status' => 1])->column('user_id');

        $status = false;
        $data = [
            'user_id' => $this->member['id'],
            'cluster_id' => $this->params['cluster_id'],
            'name' => $this->member['name'],
            'avatar' => changeUrl($this->member['head_100']),
            'noble_grade' => 0,
            'noble_icon' => '',
            'car_cover' => '',
        ];

        if ($this->member['noble_time'] > time() && $this->member['noble_grade']) {
            $data['noble_grade'] = $this->member['noble_grade'];

            $gradeNoble = GradeNoble::get(['grade' => $this->member['noble_grade']]);

            if ($gradeNoble) {

                $privilege = explode(',', $gradeNoble['privilege']);

                if (in_array(3, $privilege)) {
                    $data['noble_icon'] = changeUrl($gradeNoble['icon']);

                    $status = true;
                }
            }
        }

        $userCar = Db::name('user_car t1')
            ->field('t2.cover')
            ->join('car t2', 't2.id = t1.car_id')
            ->where(['t1.user_id' => $this->member['id'], 't1.expire' => ['gt', time()], 't1.is_select' => 1])
            ->find();

        if ($userCar) {
            $data['car_cover'] = changeUrl($userCar['cover']);

            $status = true;
        }

        if ($status) {
            $message = json_encode(['code' => 200, 'action' => 'api/Cluster/enter', 'data' => $data]);

            foreach ($ids as $key => $item) {
                $ids[$key] = getenv('SOCKET_PREFIX') . $item;
            }
            Gateway::sendToUid($ids, $message);
        }
    }

}
